<template>
  <el-form-item label="多行省略">
    <el-radio-group v-model="editorForm.lineClamp.isDefault" @change="handleDefault">
      <el-radio :label="true">默认</el-radio>
      <el-radio :label="false">自定义</el-radio>
    </el-radio-group>
    <div v-if="!editorForm.lineClamp.isDefault" class="custom-after">
      <el-input-number v-model="editorForm.lineClamp.value" :min="1" :precision="0" size="small" @change="handleChange" />
    </div>
  </el-form-item>
</template>

<script setup>
import { inject, ref, onMounted } from 'vue'
import { pxToRem } from '@/utils/tools'

const { editorForm, domList, changeDefault, backUpdate } = inject('commonForm')
// 初始化属性和元素对应关系
const bindDom = ref(new Set())
const initDomMapping = () => {
  const bindKeys = [`${editorForm.value._key}.lineClamp.value`]
  domList.value.forEach(element => {
    const bindValue = element.getAttribute('_bind')
    bindKeys.forEach(key => {
      if (bindValue.includes(key)) {
        bindDom.value.add(element)
      }
    })
  })
}

const handleDefault = (val) => {
  if (val) {
    changeDefault('lineClamp')
  }
  bindDom.value.forEach(element => {
    element.style.lineClamp = editorForm.value.lineClamp.value
    const computedStyle = window.getComputedStyle(element)
    const lineHeightWithUnit = computedStyle.lineHeight
    const lineHeight = parseFloat(lineHeightWithUnit)
    element.style.maxHeight = pxToRem(lineHeight * editorForm.value.lineClamp.value)
  })
  if (bindDom.value.size === 0) {
    backUpdate()
  }
}

const handleChange = () => {
  bindDom.value.forEach(element => {
    element.style.lineClamp = editorForm.value.lineClamp.value
    const computedStyle = window.getComputedStyle(element)
    const lineHeightWithUnit = computedStyle.lineHeight
    const lineHeight = parseFloat(lineHeightWithUnit)
    element.style.maxHeight = pxToRem(lineHeight * editorForm.value.lineClamp.value)
  })
  if (bindDom.value.size === 0) {
    backUpdate()
  }
}

onMounted(() => {
  initDomMapping()
})

</script>

<style lang="scss" scoped>

</style> 